<?php

class AclController extends Zend_Controller_Action {

    public function preDispatch() {
        $t = Zend_Registry::get('Zend_Locale');
        $this->view->navigation_line = array($t->_('Users & groups') => ADMIN_URL . '/acl');
        $auth = Zend_Auth::getInstance();
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        }
    }

    public function access() {
        $session = new Zend_Session_Namespace('UnCMS');
        if (!isset($session->acl->users))
            $this->_redirect(SITE_URL);
    }

    public function indexAction() {
        $this->access();
        $model = new AclModel();
        $this->view->groups = $model->getGroups();
        $this->view->users = $model->getUsers();
    }

    /**
     * Управление правами у объекта
     */
    public function aclAction() {
        /*
         * Проверить права на сам объект, если нет - ругнуться
         */
        $model = new AclModel();
        $form = new AclForm();
        $oid = (int) $this->getRequest()->getParam('oid', 0);
        $aid = (int) $this->getRequest()->getParam('aid', 0);
        $object = htmlentities($this->getRequest()->getParam('object', 0));

        $acls = $model->getAcls($object, $oid);
        $session = new Zend_Session_Namespace('UnCMS');

        $max_acl = 0;
        foreach ($session->groups as $key => $value) {
            if (isset($acls[$value]) && $max_acl < $acls[$value]) {
                $max_acl = $acls[$value];
            }
        }
        $auth = Zend_Auth::getInstance();
        $obj = $model->getObject($object, $oid);

        if ($auth->getIdentity()->id == 1)
            $max_acl = 10;
        if (isset($obj) && $auth->getIdentity()->id == $obj->aid)
            $max_acl = 10;
        $this->view->form = $form->Acl($object, $oid);
        $this->view->max_acl = $max_acl;
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($max_acl >= 3) {
                $model->updateAcls($object, $oid, $formData);
            }
        } else {
            $form->populate($acls);
        }
    }

    /**
     * Страница редактирования группы
     */
    public function groupAction() {
        $this->access();
        $model = new AclModel();
        $form = new AclForm();
        $gid = (int) $this->getRequest()->getParam('id', 0);
        $this->view->gid = $gid;
        $this->view->form = $form->Group($gid);
        $t = Zend_Registry::get('Zend_Locale');
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                $users = & $formData['users'];
                $group['name'] = & $formData['name'];
                $group['description'] = & $formData['description'];
                if (isset($formData['admin']) && isset($formData['modules'])) {
                    $acls = array_merge($formData['admin'], $formData['modules']);
                } else {
                    if (isset($formData['admin']))
                        $acls = $formData['admin'];
                    if (isset($formData['modules']))
                        $acls = $formData['modules'];
                }
                $group['acls'] = implode("|", $acls);
                $pid = $model->updateGroup($group, $gid);
                $entry = $model->updateEntry($users, $gid, true);
                $this->_redirect('/acl/');
            } else {
                $form->populate($formData);
            }
        }
        if ($gid > 0) {
            $group = $model->getGroups($gid);
            $this->view->navigation_line = $this->view->navigation_line + array($t->_('Group &laquo;') . $group->name . '&raquo;' => ADMIN_URL . '/acl/group/id/' . $group->id);
            $acls = explode('|', $group->acls);
            $entry = $model->getEntry($gid, true);
            $form->populate((array) $group + array('admin' => $acls) + array('modules' => $acls) + array('users' => $entry));
            $this->view->group = $group;
        } else {
            $this->view->navigation_line = $this->view->navigation_line + array($t->_('Add group') => ADMIN_URL . '/acl/group/');
        }
    }

    /**
     * Страница редактирования пользователя
     */
    public function userAction() {
        //$this->access();
        $model = new AclModel();
        $form = new AclForm();

        $uid = (int) $this->getRequest()->getParam('id', 0);

        $session = new Zend_Session_Namespace('UnCMS');
        if (!isset($session->acl->users)) {
            $uid = USER_ID;
            $this->view->onlyme = true;
        } else {
            $this->view->onlyme = false;
        }

        $this->view->uid = $uid;

        $this->view->form = $form->User($uid, $this->view->onlyme);
        $t = Zend_Registry::get('Zend_Locale');
        if ($this->_request->isPost()) {//Форма отправлена
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                if (isset($formData['groups']))
                    $groups = array_pop($formData);
                $uid = $model->updateUser($formData, $uid);
                if (!$this->view->onlyme) {
                    $model = $model->updateEntry($groups, $uid);
                    $this->_redirect('/acl/');
                } else {
                    $this->_redirect('/');
                }
                
            } else {
                $form->populate($formData);
            }
        }
        if ($uid > 0) {//Забиваем форму и навигацию, определяем переменные шаблона
            $user = $model->getUsers($uid);
                if (!$this->view->onlyme) {
                    $this->view->navigation_line = $this->view->navigation_line + array($t->_('User &laquo;') . $user->name . '&raquo;' => ADMIN_URL . '/acl/user/id/' . $user->id);
                } else {
                    $this->view->navigation_line = array($t->_('User &laquo;') . $user->name . '&raquo;' => ADMIN_URL . '/acl/user/id/' . $user->id);
                }
            
            $entry = $model->getEntry($uid);
            $form->populate((array) $user + array('groups' => $entry));
            $this->view->user = $user;
        } else {
            $this->view->navigation_line = $this->view->navigation_line + array($t->_('Add user') => ADMIN_URL . '/acl/user/');
        }
    }

    public function loginAction() {

        $layout = Zend_Layout::getMvcInstance();
        $layout->setLayout('login');
        $t = Zend_Registry::get('Zend_Locale');
        $model = new AclModel();
        $forms = new AclForm();
        $form = $forms->Login();
        $this->view->form = $form;
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if (!$model->authentification($formData['login'], $formData['password'])) {
                $this->view->error = $t->_('Sorry, unrecognized username or password.');
            } else {
                $this->_redirect(ADMIN_URL);
            }
        }
    }

    /**
     * Выход
     */
    public function exitAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }

    public function deleteAction() {

        $session = new Zend_Session_Namespace('UnCMS');

        if (!isset($session->acl->users)) {
            $uid = USER_ID;
        } else {
            $uid = (int) $this->_getParam('uid');
            $gid = (int) $this->_getParam('gid');
        }

        $model = new AclModel();
        if ($uid > 1) {
            $model->deleteUser($uid);
            if ($uid == USER_ID) {
                Zend_Auth::getInstance()->clearIdentity();
                $this->_redirect('/');
            }
        } else if ($gid > 0) {
            $model->deleteGroup($gid);
        }
        $this->_forward('index', 'acl');
    }

}
